from flask import render_template, redirect, url_for, jsonify, request, session
from flask_login import login_required, current_user 
from app.main import main
from app import mailbox
from app.mq import MQ
from time import sleep


@main.route('/')
def home():
    return render_template("auth/index.html")


@main.route('/lpoll')
@login_required
def lpoll():
    username = current_user.user_name
    ack = request.args.get('ack')
    first = request.args.get('first')

    if username not in mailbox:
        mailbox[username] = MQ(maxsize=5)
    mq = mailbox[username]
    noti = None

    if ack == '0':
        if not mq.get_ack():
            return jsonify(mq.buf_msg)
    else:
        mq.set_ack(True)

    # kill a waiting thread
    if first:
        mq.queue.put({})
        sleep(1)
    flag = mq.get_flag()

    try:
        # blocking get, thread-safe
        noti = mq.queue.get(timeout=40)

        # this thread is ask to die
        if not noti:
            return jsonify()
        if mq.get_flag() != flag:
            mq.queue.put_nowait(noti)
            return jsonify(mq.buf_msg)

        mq.set_ack(False)
        mq.add_flag()
        mq.buf_msg = noti            
        return jsonify(noti)
    except Exception as e:
        if mq.get_flag() != flag and not mq.get_ack():
            return jsonify(mq.buf_msg)
        return jsonify()